<template>
  <div class="main-content">
    <div class="newbtn">
      <a-button
        type="primary"
        @click="
          () => {
            AddSemester();
          }
        "
        >添加新学期</a-button
      >
    </div>
    <div class="userlist">
      <a-table
        :pagination="pagination"
        :loading="loading"
        @change="handlePageChange"
        :dataSource="dataSource"
        :columns="columns"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action'">
            <a-space wrap>
              <a-button
                size="small"
                type="primary"
                :disabled="record.activate === 1"
                @click="
                  async () => {
                    await setAsCurrentSemester(record.id);
                  }
                "
                >设为当前学期</a-button
              >
              <a-button
                size="small"
                type="primary"
                @click="
                  async () => {
                    await showEditModal(record);
                  }
                "
                >修改学期信息</a-button
              >
              <a-button
                danger
                size="small"
                @click="
                  async () => {
                    await deleteSemester(record.id);
                  }
                "
                >删除该学期</a-button
              >
            </a-space>
          </template>
        </template>
      </a-table>

      <a-modal
        v-model:visible="addModalVisible"
        title="添加新学期"
        okText="保存"
        cancelText="取消"
        centered="true"
        @ok="confirmAddSemester"
        @cancel="closeAddModal"
      >
        <a-form layout="vertical">
          <a-form-item label="学期名称">
            <a-input
              v-model:value="newSemester.name"
              placeholder="格式为：xxxx-xxxx-x"
              required
            />
          </a-form-item>
          <a-form-item label="周数">
            <a-input-number
              v-model:value="newSemester.weeksNum"
              min="1"
              max="22"
              style="width: 100%"
              placeholder="请输入周数"
              required
            />
          </a-form-item>
        </a-form>
      </a-modal>

      <a-modal
        v-model:visible="editModalVisible"
        title="修改学期信息"
        okText="保存"
        cancelText="取消"
        centered="true"
        @ok="confirmEditSemester"
        @cancel="closeEditModal"
      >
        <a-form layout="vertical">
          <a-form-item label="学期名称">
            <a-input
              v-model:value="editSemester.name"
              placeholder="格式为：xxxx-xxxx-x"
              required
            />
          </a-form-item>
          <a-form-item label="周数">
            <a-input-number
              v-model:value="editSemester.weeksNum"
              min="1"
              max="20"
              style="width: 100%"
              placeholder="请输入周数"
              required
            />
          </a-form-item>
        </a-form>
      </a-modal>

      <a-modal
        v-model:visible="deleteModalVisible"
        title="删除学期确认"
        okText="确认删除"
        cancelText="取消"
        centered="true"
        @ok="confirmDeleteSemester"
        @cancel="closeDeleteModal"
      >
        <p>您确定要删除该学期吗？此操作不可恢复。</p>
      </a-modal>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref } from "vue";
import {
  semesterQuery,
  semesterDelete,
  semesterSet,
  semesterAdd,
  semesterUpdate,
} from "../../api/methods/semesterReq";
import { omit } from "lodash";
import { IRepairInfo } from "@/api/RequestIDL/repairLogType";
import { message } from "ant-design-vue";

import semesterName from "@/store/semesterName";

const semesterNameStore = semesterName();
interface IPagenation {
  current: number;
  pageSize: number;
  total: number;
}
const pagination = computed(() => {
  return {
    total: pageConfig.value.total,
    current: pageConfig.value.page,
    pageSize: pageConfig.value.pageSize,
  };
});

const columns = [
  { title: "学期ID", dataIndex: "id", key: "id", width: "" },
  { title: "学期", dataIndex: "name", key: "name" },
  { title: "周数", dataIndex: "weeksNum", key: "weeksNum" },
  { title: "操作", dataIndex: "action", key: "action", width: "200px" },
];

const pageConfig = ref({
  total: 0,
  page: 1,
  pageSize: 10,
});
const loading = ref(false);
const dataSource = ref([]);
const deleteModalVisible = ref(false);
const deleteTargetSemesterId = ref("");
const formInfo = ref<Partial<IRepairInfo>>({});

const handlePageChange = async (pagination: IPagenation) => {
  pageConfig.value.page = pagination.current;
  pageConfig.value.pageSize = pagination.pageSize;
  loading.value = true;
  const res = await semesterQuery({
    page: pageConfig.value.page,
    pageSize: pageConfig.value.pageSize,
    name: "",
  });
  dataSource.value = res.data.records.map((item: any) => {
    return {
      ...item,
    };
  });

  loading.value = false;
};

onMounted(async () => {
  loading.value = true;
  const res = await semesterQuery({
    page: pageConfig.value.page,
    pageSize: pageConfig.value.pageSize,
    name: "",
  });
  pageConfig.value.total = res.data.total;
  dataSource.value = res.data.records.map((item: any) => {
    return {
      ...item,
    };
  });
  loading.value = false;
  
});

const reloadData =async()=>{
  loading.value=true;
  const res=await semesterQuery({
    page:pageConfig.value.page,
    pageSize:pageConfig.value.pageSize,
    name:"",
  });
  pageConfig.value.total=res.data.total;
  dataSource.value = res.data.records.map((item: any) => {
    return {
      ...item,
    };
  });

  const activeSemester = dataSource.value.find(
    (semester: any) => semester.activate === 1
    );
    if (activeSemester) {
     semesterNameStore.changeSemester(activeSemester.name,activeSemester.id);
     }

  loading.value = false;
  
}


async function setAsCurrentSemester(semesterId: string) {
  try {
    await semesterSet({ id: semesterId });
    message.success("设置当前学期成功");
    
    await reloadData();
  } catch (error) {
    message.error("设置当前学期失败");
  }
}

async function deleteSemester(semesterId: string) {
  deleteTargetSemesterId.value = semesterId;
  deleteModalVisible.value = true;
}

async function confirmDeleteSemester() {
  await semesterDelete({id:deleteTargetSemesterId.value});
  closeDeleteModal();
  await reloadData();
}

function closeDeleteModal() {
  deleteModalVisible.value = false;
  deleteTargetSemesterId.value = "";
}

const editModalVisible = ref(false);
const editSemester = ref({
  id: "",
  name: "",
  weeksNum: 0,
});

async function showEditModal(record: any) {
  editSemester.value = {
    id: record.id,
    name: record.name,
    weeksNum: record.weeksNum,
  };
  editModalVisible.value = true;
}

async function confirmEditSemester() {
  try {
    await semesterUpdate(editSemester.value);
    message.success("修改学期信息成功");
    closeEditModal();

    await handlePageChange(pagination.value);
    await reloadData();
  } catch (error) {
    message.error("修改学期信息失败");
  }
}

function closeEditModal() {
  editModalVisible.value = false;
  editSemester.value = {
    id: "",
    name: "",
    weeksNum: 0,
  };
}

const addModalVisible = ref(false);
const newSemester = ref({
  name: "",
  weeksNum: 1,
});

function AddSemester() {
  addModalVisible.value = true;
  newSemester.value = {
    name: "",
    weeksNum: 0,
  };
}

async function confirmAddSemester() {
  try {
    await semesterAdd(newSemester.value);
    message.success("添加新学期成功");
    closeAddModal();

    // 刷新表格数据以显示新增的学期
    await handlePageChange(pagination.value);
    await reloadData();
  } catch (error) {
    message.error("添加新学期失败");
  }
}

function closeAddModal() {
  addModalVisible.value = false;
  newSemester.value = {
    name: "",
    weeksNum: 0,
  };
}
</script>
<style scoped lang="scss">
/* @import url(); 引入css类 */
.main-content {
  .newbtn {
    margin-bottom: 15px;
  }
}
</style>
